package com.qf.hospital.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.hospital.entity.SysMenu;
import com.qf.hospital.entity.SysMenuExample;
import com.qf.hospital.enums.HospitalErrorEnums;
import com.qf.hospital.exception.HospitalException;
import com.qf.hospital.mapper.SysMenuMapper;
import com.qf.hospital.service.SysMenuService;
import com.qf.hospital.util.ExampleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Administrator
 * @version V1.0
 * @Project hospital
 * @Package com.qf.hospital.service.impl
 * @Description: ${TODO}
 * @Date 2021/10/19 11:03
 */

@Service
public class SysMenuServiceImpl implements SysMenuService {

    private Logger log = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    @Autowired
    private SysMenuMapper menuMapper;

    @Override
    public List<SysMenu> findAll() {

        //1. 封装条件
        SysMenuExample example = new SysMenuExample();
        SysMenuExample.Criteria criteria = example.createCriteria();
        criteria.andAvailableEqualTo(1);
        //2. 查询并返回
        return menuMapper.selectByExample(example);
    }

    @Override
    public PageInfo<SysMenu> findByTitle(String title, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);

        SysMenuExample example = new SysMenuExample();
        SysMenuExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(title)){
            criteria.andTitleLike(ExampleUtil.any(title));
        }
        List<SysMenu> menuList = menuMapper.selectByExample(example);
        PageInfo<SysMenu> pageInfo = new PageInfo<>(menuList);
        return pageInfo;
    }

    @Override
    public Integer findParentId(Integer id) {
        SysMenu menu = menuMapper.findById(id);
        Integer parentId = menu.getParentId();
        if (parentId != 0 && parentId != 1){
            return 1;
        }
        return 0;
    }

    @Override
    public void deleteById(Integer id) {
        menuMapper.deleteByPrimaryKey(id);
    }



    @Override
    public void addMenu(SysMenu menu) {
        int count = menuMapper.insertSelective(menu);
        if (count != 1){
            log.error("【添加菜单】 添加失败 menu = {} ",menu);
            throw new HospitalException(HospitalErrorEnums.MENU_ADD_ERROR);
        }
    }

    @Override
    public void updateMenu(SysMenu sysMenu) {
        int i = menuMapper.updateByPrimaryKeySelective(sysMenu);
        if (i != 1){
            log.error("【编辑菜单】 编辑失败 sysMenu",sysMenu);
            throw new HospitalException(HospitalErrorEnums.MENU_UPDATE_ERROR);
        }
    }


}
